
<template>
  <div class="course-container">
    <!-- 树形侧边栏 -->
    <div class="sidebar">
      <div class="sidebar_header">
          <span>课程管理</span>
          <!-- <el-button type="warning" @click="exportData">导入导出</el-button> -->
          <el-button @click="showAddDialog()">添加课程</el-button>

      </div>
      <div class="search">
        <el-input class="search-input" v-model="searchInput" placeholder="请输入查询条件"></el-input>
        <el-select style="margin-top: 5px;" clearable v-model="courseTypeNum" placeholder="请选择课程分类" class="w-full">
            <el-option
              v-for="item in courseType"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        <div style="margin-top:10px; margin-left:35%">
          <el-checkbox style="position:relative;top:5px;left:-6px" v-model="isCollapsed" @change="handleCollapseChange">{{isCollapsed ? "全部展开" : "全部折叠"}}</el-checkbox>

          <!-- <div style="margin-top:10px; margin-left:63%"> -->
          <el-button type="primary" :disabled="loading" @click="searchChange(searchInput,courseTypeNum)">搜索</el-button>
          <el-button :disabled="loading" @click="searchChange()">重置</el-button>
        </div>

      </div>
      <TreeMenu
        ref="treeMenuRef"
        v-loading="loading"
        :data="menuData"
        @node-click="handleNodeClick"
        @menuType="menuType"
        style="height:80vh"
      />
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <AddCourse
        v-if="datas.type == 1"
        ref="addCourseDialogRef"
        :title="title"
        :isEdit="isEdit"
        :courseData="currentCourseData"
        @submit="handleCourseSubmit"
        @delete="handleCourseDelete"
      />
      <AddChapter
        v-if="datas.type == 2"
        :isEdit="isEdit"
        :courseId="currentCourseId"
        :chapterData="currentChapterData"
        @refresh="refreshTreeList"
        @cancel="handleChapterCancel"
      />
      <AddVideo
        ref="checdVideo"
        v-else-if="datas.type == 3"
        :isEdit="isEdit"
        :formData="videoFromData"
        @update:formDatas="handleUpdate"
        @submit="handleVideoSubmit"
        @cancel="handleVideoCancel"
        @delete="handleVideoDelete"
      />
      <Video v-else-if="datas.type == 4" :videoUrl="defaultVideoUrl" :title="videoTitle" />
    </div>
    <XlsxModel :xlsxModel="xlsxModel"></XlsxModel>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import TreeMenu from './TreeMenu.vue'
import AddVideo from './AddVideo.vue'
import Video from './components/video.vue'
import { getTreeListInfo, addTreeFirstCourse, editTreeFirstCourse, getCourseInfo, delCourseInfo } from '@/api/bykt/course'
import { getChapterInfo } from '@/api/bykt/chapter'
import { addVideo, editVieo, deltVieo, getVideoInfo } from '@/api/bykt/video'
import AddChapter from './components/AddChapter.vue'
import AddCourse from './components/addCourse.vue'
import { ElMessage } from 'element-plus'
import XlsxModel from './components/xlsx'
import {getCategoryTypeList} from '@/api/bykt/course/index';

const xlsxModel = ref(false)
const courseTypeNum = ref('')
const addCourseDialogRef = ref()
const loading = ref(false)
const datas = reactive({
    type: 1,
})
const currentChapterData = ref({})
const currentCourseId = ref('')
const searchInput = ref('')
const isEdit = ref(false)
const currentCourseData = ref({})
const defaultVideoUrl = ref('')

const videoFromData = ref({
  title: '',
  description: '',
  coverImage: '',
  url: '',
  sort: 1,
  duration: 0,
  isFree: 0,  // 默认免费
  viewCount: 0 // 默认观看次数为0
})

const checdVideo = ref(null)
const videoClear = () => {
  console.log('清空视频',checdVideo)
  checdVideo.value.clearVideo()
}
const handleUpdate = (newData) => {
  console.log('更新后的表单数据:', newData)
  // videoFromData.value = newData
  videoFromData.value.url = newData.url
  console.log('更新后的表单数据:', videoFromData)
}
const videoTitle = ref('')
const title = ref('新增课程')
const courseType = ref([])
const menuData = ref([
  {
    id: 1,
    name: '课程列表',
    type: 1,
    children: []
  },
  {
    id: 2,
    name: '视频列表',
    type: 2,
    children: []
  }
])

const exportData = () => {
  xlsxModel.value = true
}
// 清空课程数据
const clearCourseData = () => {
  currentCourseData.value = {}
  addCourseDialogRef.value.resetForm()
}

// 显示新增课程对话框
const showAddDialog = () => {
  datas.type = 1
  title.value = '新增课程'
  isEdit.value = false
  clearCourseData()
  addCourseDialogRef.value.dialogVisible = true
}

// 处理课程提交（新增/编辑）
const handleCourseSubmit = async (formData) => {
  try {
    if (isEdit.value) {
      // 编辑课程
      const res = await editTreeFirstCourse(formData)
      if (res.code === 200) {
        ElMessage.success('编辑成功')
        // 111
        requestTreeList() // 刷新列表
      }
    } else {
      // 新增课程
      const res = await addTreeFirstCourse(formData)
      if (res.code === 200) {
        ElMessage.success('添加成功')
        clearCourseData() // 清空表单
        requestTreeList() // 刷新列表
      }
    }
  } catch (error) {
    console.error('操作失败：', error)
    ElMessage.error('操作失败')
  }
}

// 处理节点点击
const handleNodeClick = async (node) => {
  datas.type = 0
  if (node.type === 1) {
    try {
      const res = await getCourseInfo(node.id)
      if (res.code === 200) {
        title.value = '编辑课程'
        isEdit.value = true
        currentCourseData.value = res.data
        datas.type = node.type
      }
    } catch (error) {
      console.error('获取课程信息失败：', error)
      ElMessage.error('获取课程信息失败')
      datas.type = node.type
    }
  } else if (node.type === 2) {
    datas.type = 0
    // 处理章节点击
    try {
      const res = await getChapterInfo(node.id)
      console.log('章节数据:', res) // 添加日志，查看返回数据
      if (res.code === 200) {
        title.value = '编辑章节'
        isEdit.value = true
        currentChapterData.value = {...res.data} // 使用解构赋值确保响应式更新
        currentCourseId.value = res.data.courseId
        datas.type = node.type
      }
    } catch (error) {
      console.error('获取章节信息失败：', error)
      ElMessage.error('获取章节信息失败')
      datas.type = node.type
    }
  } else if (node.type === 3) {
    // 处理视频点/击
    // try {
    datas.type = 0

    try {
      const res = await getVideoInfo(node.id)
      if (res.code === 200) {
        title.value = '编辑视频'
        isEdit.value = true
        videoFromData.value = {...res.data} // 使用解构赋值确保响应式更新
        datas.type = node.type
      }
    } catch (error) {
      console.error('获取视频信息失败：', error)
      ElMessage.error('获取视频信息失败')
      datas.type = node.type
    }
  }
}

const menuType = async (type, item) => {
  console.log(item)
  isEdit.value = false
  if (type == 1) {
    // 新增章节
    datas.type = type + 1
    title.value = '新增章节'
    // 清空章节数据
    currentChapterData.value = {}
    currentCourseId.value = item.id
  } else if (type == 2) {
    // 新增视频
    datas.type = 0
    title.value = '新增视频'
    // 确保完全清空videoFromData
    videoFromData.value = {
      title: '',
      description: '',
      url: '',
      sort: 1,
      duration: 0,
      isFree: 0,  // 默认免费
      viewCount: 0, // 默认观看次数为0
      courseId: item.courseId, // 如果是在课程下添加，使用item.id，如果是在章节下添加，使用item.courseId
      chapterId: item.type === 2 ? item.id : null // 如果是在章节下添加，设置chapterId
    }
    setTimeout(() => {
      datas.type = type + 1
    }, 1);

  } else if (type == 3) {
    // 查看视频 - 使用API获取最新视频信息
    loading.value = true // 显示加载状态
    try {
      const res = await getVideoInfo(item.id)
      console.log('视频数据:', res) // 添加日志，查看返回数据
      if (res.code === 200) {
        defaultVideoUrl.value = res.data.url
        videoTitle.value = res.data.title
        // datas.type = 0 // 切换到视频播放组件
        setTimeout(() => {
         datas.type = 4 // 切换到视频播放组件
        }, 1);
      } else {
        ElMessage.error('获取视频信息失败')
      }
    } catch (error) {
      console.error('获取视频信息失败：', error)
      ElMessage.error('获取视频信息失败')
    } finally {
      loading.value = false // 隐藏加载状态
    }
  }
}
// 处理视频提交
const handleVideoSubmit = async (formData) => {
  console.log('提交的表单数据:', formData)
  try {
    if (isEdit.value) {
      // 编辑视频
      const res = await editVieo(formData)
      if (res.code === 200) {
        ElMessage.success('编辑成功')
        refreshTreeList() // 刷新列表
        videoClear()
         // 刷新组件
         datas.type = 0
        setTimeout(() => {
          datas.type = 3 // 切换到新增视频页面
        }, 1)
      }
    } else {
      // 新增视频
      const res = await addVideo(formData)
      if (res.code === 200) {
        ElMessage.success('添加成功')
        refreshTreeList() // 刷新列表
        videoClear()
        videoFromData.value = {
          title: '',
          description: '',
          url: '',
          sort: undefined,
          duration: undefined,
          isFree: undefined,  // 默认免费
          viewCount: undefined, // 默认观看次数为0
          courseId: videoFromData.value.courseId, // 如果是在课程下添加，使用item.id，如果是在章节下添加，使用item.courseId
          chapterId: videoFromData.value.chapterId, // 如果是在章节下添加，设置chapterId
        }
      }
    }
  } catch (error) {
    console.error('操作失败：', error)
    ElMessage.error('操作失败')
  }
}

// 处理视频取消
const handleVideoCancel = () => {
  datas.type = 1 // 返回到课程列表
  videoFromData.value = {
    title: '',
    description: '',
    url: '',
    sort: 1,
    duration: 0,

    isFree: 0,  // 默认免费
    viewCount: 0 // 默认观看次数为0
  }
}

// 处理视频删除
const handleVideoDelete = async (videoId) => {
  try {
    const res = await deltVieo(videoId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      refreshTreeList() // 刷新列表
      // 保存当前的 courseId 和 chapterId
      const currentCourseId = videoFromData.value.courseId
      const currentChapterId = videoFromData.value.chapterId
      // 重置表单数据，但保留 courseId 和 chapterId
      videoFromData.value = {
        title: '',
        description: '',
        url: '',
        sort: 1,
        duration: 0,
        isFree: 0,
        viewCount: 0,
        courseId: currentCourseId,
        chapterId: currentChapterId
      }
      videoClear()
      isEdit.value = false
      // 刷新组件以切换到新增视频页面
      datas.type = 0
      setTimeout(() => {
        datas.type = 3
      }, 1)
    }
  } catch (error) {
    console.error('删除失败：', error)
    ElMessage.error('删除失败')
  }
}

// 添加章节取消处理方法
const handleChapterCancel = () => {
  datas.type = 1 // 返回到课程列表
}

const searchChange = (value,categoryId) => {
  // console.log('搜索',value, courseId)
  requestTreeList({title: value,categoryId:categoryId})
  if (!value && !categoryId) {
    searchInput.value = ''
    courseTypeNum.value = ''
  }
}

const requestTreeList = (val) => {
  console.log(val)
  const data = {
    title:searchInput.value,
    categoryId:courseTypeNum.value
  }
  loading.value = true
  getTreeListInfo(data).then(res => {
    if (res.code === 200) {
      menuData.value = res.data
      loading.value = false
    }
  })
}

// 处理课程删除
const handleCourseDelete = async (courseId) => {
  try {
    const res = await delCourseInfo(courseId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 刷新列表
      requestTreeList()
      // 切换到新增课程状态
      showAddDialog()
    }
  } catch (error) {
    console.error('删除失败：', error)
    ElMessage.error('删除失败')
  }
}
// 刷新树列表
const refreshTreeList = () => {
  requestTreeList()
}
const fetchCourseTypeList = async () => {
  try {
    const res = await getCategoryTypeList({});
    courseType.value = res.rows || [];
  } catch (error) {
    console.error("获取课程分类列表失败:", error);
  }
};

// ... existing code ...
const isCollapsed = ref(false)
const treeMenuRef = ref(null)

const handleCollapseChange = (checked) => {
  // 调用 TreeMenu 组件的 toggleAll 方法
  console.log(checked)
  treeMenuRef.value?.toggleAll(checked)
}
onMounted(() => {
  requestTreeList()
  fetchCourseTypeList()
})
</script>

<style scoped>
.course-container {
  display: flex;
  /* height: 100vh; */
}
.sidebar {
  width: 400px;
  border-right: 1px solid #eee;
  overflow-y: auto;
}
.main-content {
  flex: 1;
  padding: 20px;
}
.sidebar_header {
  padding: 10px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  span {
    flex: 1;
    font-size: 18px;
    font-weight: bold;
  }
}
.search-input {
  /* width: 200px; */
}
</style>



<style scoped>
.course-container {
  display: flex;
  /* height: 100vh; */
}
.sidebar {
  width: 400px;
  border-right: 1px solid #eee;
  overflow-y: auto;
}
.main-content {
  flex: 1;
  padding: 20px;
}
.sidebar_header {
  padding: 10px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  span {
    flex: 1;
    font-size: 18px;
    font-weight: bold;
  }
}
.search-input {
  /* width: 200px; */
}
</style>


